<template>
  <div class="news-box">
    <el-card class="box-card" shadow="never">
      <div class="search-box" style="overflow: hidden">
        <div class="search-left">
          <el-icon>
            <Search />
          </el-icon>
          <span>筛选搜索</span>
        </div>

        <div class="search-right">
          <el-button @click="resetFun" class="reset-btn">
            <span>重置</span>
          </el-button>
          <el-button type="primary" @click="getLists" class="el-button">
            <span>查询结果</span>
          </el-button>
        </div>
      </div>

      <el-form :model="search" ref="searchForm" label-width="100px" class="search-form" style="overflow-x: auto">
        <el-form-item label="状态:" prop="weihuren">
          <el-select v-model="search.status" class="m-2" placeholder="状态" size="large" @change="getLists" clearable>
            <el-option v-for="item in statusArr" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单号:" prop="name">
          <el-input v-model="search.name" size="large" placeholder="请输入内容" @change="getLists" clearable></el-input>
        </el-form-item>
        <el-form-item label="联系电话:" prop="tel">
          <el-input v-model="search.tel" size="large" placeholder="请输入内容" @change="getLists" clearable></el-input>
        </el-form-item>
        <el-form-item label="取件人名称:" prop="consignee">
          <el-input v-model="search.consignee" size="large" placeholder="请输入内容" @change="getLists" clearable></el-input>
        </el-form-item>
        <el-form-item label="省市区:" prop="address">
          <el-cascader placeholder="请选择地区" size="large" :options="provinceAndCityData" v-model="search.address"
            @change="handleChange" clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="仓库:" prop="cangkuid">
          <el-select v-model="search.cangkuid" class="m-2" placeholder="仓库" size="large" @change="getLists" clearable>
            <el-option v-for="item in cangkus" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号查询:" prop="wuliu_sn">
          <el-input v-model="search.wuliu_sn" size="large" placeholder="请输入内容" @change="getLists" clearable></el-input>
        </el-form-item>
        <el-form-item label="创建时间:" prop="dateRang">
          <el-date-picker v-model="search.dateRang" type="daterange" range-separator="到" start-placeholder="开始时间"
            end-placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" size="large" @change="getLists" />
        </el-form-item>
        <el-form-item label="验货时间:" prop="yanhuoRang">
          <el-date-picker v-model="search.yanhuoRang" type="daterange" range-separator="到" start-placeholder="开始时间"
            end-placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" size="large" @change="getLists" />
        </el-form-item>
        <el-form-item label="详细地址:" prop="postcode">
          <el-input v-model="search.postcode" size="large" placeholder="请输入内容" @change="getLists" clearable></el-input>
        </el-form-item>
        <el-form-item label="用户id:" prop="userid">
          <el-input v-model="search.userid" size="large" placeholder="请输入内容" @change="getLists" clearable></el-input>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- <el-card class="table-card">
      <template #header>
        <el-button @click="addLists()" size="large" icon="Plus">添加书籍</el-button>
      </template>
    </el-card> -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header-box">
          <div>
            <!-- <el-button @click="addLists()" size="large" icon="Plus">添加书籍</el-button>
            <el-button @click="addPiLiangLists()" size="large" icon="Plus">批量添加书籍</el-button> -->
          </div>

          <el-button type="primary" @click="exportTableFun" class="el-button">
            <span>导出表格</span>
          </el-button>
        </div>
      </template>
    </el-card>
    <el-table :data="lists" border style="width: 100%" @row-click="rowCli" :row-class-name="tableRowClassName">
      <!-- <el-table-column prop="id" label="编号" align="center" width="80px" header-align="center"></el-table-column> -->

      <el-table-column prop="order_sn" label="订单号" align="center" header-align="center"></el-table-column>

      <!-- <el-table-column prop="images" label="封面" align="center" header-align="center">
        <template #default="scope">
          <img style="width: 100px; height: 120px" :src="scope.row.list[0].images" alt="" />
        </template>
      </el-table-column> -->

      <!-- <el-table-column prop="list[0].name" label="书籍名称" align="center" header-align="center"> </el-table-column> -->

      <!-- <el-table-column prop="list[0].isbn" label="ISBN编码" align="center" header-align="center"></el-table-column> -->

      <el-table-column prop="cangkuname" label="仓库名" align="center" header-align="center"></el-table-column>

      <el-table-column prop="shujishuliang" label="数量" align="center" header-align="center"></el-table-column>

      <!-- <el-table-column prop="list[0].price" label="单价" align="center" header-align="center"></el-table-column> -->

      <el-table-column prop="price" label="总价" align="center" header-align="center"></el-table-column>

      <el-table-column prop="createtime" label="时间" align="center" header-align="center"></el-table-column>

      <el-table-column prop="userid" label="用户id" align="center" header-align="center"> </el-table-column>

      <el-table-column prop="consignee" label="取件人名称" align="center" header-align="center"> </el-table-column>

      <el-table-column prop="tel" label="联系电话" align="center" header-align="center"> </el-table-column>

      <el-table-column prop="statusText" label="订单状态" align="center" header-align="center">
        <template #default="scope">
          <div :style="scope.row.statusStyle">{{ scope.row.statusText }}</div>
        </template>
      </el-table-column>

      <el-table-column prop="consignee" label="联系地址" align="center" header-align="center">
        <template #default="scope"> {{ scope.row.province }}/{{ scope.row.city }}/{{ scope.row.county }} </template>
      </el-table-column>

      <el-table-column prop="postcode" label="详细地址" align="center" header-align="center"> </el-table-column>

      <el-table-column prop="wuliu_name" label="物流公司" align="center" header-align="center"> </el-table-column>

      <el-table-column prop="wuliu_sn" label="物流单号" align="center" header-align="center"> </el-table-column>

      <el-table-column prop="houtaibeizhu" label="后台备注" align="center" header-align="center">
        <template #default="scope">
          <el-input @click.stop="" v-model="scope.row.houtaibeizhu" :rows="3" type="textarea" placeholder="后台备注" />
          <el-button type="primary" @click.stop="beizhuChange(scope.row.order_sn, scope.row.houtaibeizhu)" size="small"
            class="el-button" style="margin-top: 10px;margin-bottom: 10px">
            确认编辑
          </el-button>
        </template>
      </el-table-column>

      <el-table-column prop="qujianren" label="物流信息" align="center" header-align="center">
        <template #default="scope">
          <el-button type="primary" @click.stop="getWuliu(scope.row, 'wuliu')" size="small" class="el-button"
            style="margin-bottom: 5px">
            <span>货品物流</span>
          </el-button>
          <el-button type="primary" @click.stop="getWuliu(scope.row, 'qujian')" size="small" class="el-button"
            style="margin-left: 0">
            <span>取件信息</span>
          </el-button>
        </template>
      </el-table-column>

      <el-table-column prop="AgainDebangWuliu" label="重推德邦" align="center" header-align="center">
        <template #default="scope">
          <el-button type="primary" @click.stop="againDebangWuliuFun(scope.row.id)" size="small">
            重推德邦
          </el-button>
          <el-button type="primary" @click.stop="againJingDongWuliuFun(scope.row.id)" size="small">
            重推京东
          </el-button>
        </template>
      </el-table-column>

      <!-- <el-table-column label="操作" align="center" header-align="center" width="160px">
        <template #default="scope">
          <el-icon @click.stop="editFun(scope.row)" class="lists-edit-icon">
            <Edit />
          </el-icon>

          <el-icon @click.stop="deleteFun(scope.row.id)" class="lists-delete-icon">
            <Delete />
          </el-icon>

          <el-icon @click.stop="changeStatusFun(scope.row.id)" class="lists-delete-icon">
            <Setting />
          </el-icon>
        </template>
      </el-table-column> -->
    </el-table>
    <div style="text-align: right; margin-top: 20px; overflow: hidden">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        @prev-click="handlePrev" @next-click="handleNext" :current-page="pageNo" :page-sizes="[5, 10, 20, 50, 100]"
        :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" class="pagination">
      </el-pagination>
    </div>
    <!-- 查看物流 -->
    <wuliu :data="wuliuData" :show="wuliuShow" :status="wuliuStatus" :wuliu_sn="wuliu_sn" @hide="wuliuHide" />
  </div>
</template>
<script setup>
import { computed, onMounted, ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getOrderList, UpdateOrderHoutaibei, againDebangWuliu, AgainJingJDWuliu } from '@api/order'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/pinia/user'
import { getShujiType } from '@api/bookType'
import { getServerUserList } from '@api/person'
import { provinceAndCityData, regionData, CodeToText } from 'element-china-area-data'
import { getMyCangkuList } from '@api/cangku'
import wuliu from './components/wuliu.vue'
import { useHistoryStore } from '@/pinia/history'
import { exportTable } from '@/utils/toXLSX'

const userStore = useUserStore()

const historyStore = useHistoryStore()

const router = useRouter()

const route = useRoute()

console.log(route.path)
// *********************************************列表
const pageNo = ref(1)
const pageSize = ref(10)
const total = ref(10)
const lists = ref([])

//获取列表
const statusTextArr = ref(['已取消', '待审核', '待取件', '待收货', '待验货', '待打款', '已打款'])
const statusStyleArr = ref([
  'color: var(--dangerColor)',
  'color: var(--dangerColor)',
  'color: var(--dangerColor)',
  'color: var(--dangerColor)',
  'color: var(--dangerColor)',
  'color: var(--dangerColor)',
  'color: var(--successColor)'
])
async function getLists() {
  let { status, name, tel, isbn, shengshiqu, cangkuid, wuliu_sn, dateRang, yanhuoRang, consignee, postcode, userid } = search.value
  let searchOpt = {
    pageNo: pageNo.value,
    pageSize: pageSize.value
  }

  if (status) {
    searchOpt.status = status
  }

  if (name) {
    searchOpt.order_sn = name
  }

  if (tel) {
    searchOpt.tel = tel
  }

  if (consignee) {
    searchOpt.consignee = consignee
  }

  if (shengshiqu.length) {
    console.log(shengshiqu[0])
    searchOpt.province = shengshiqu[0]
    searchOpt.city = shengshiqu[1]
    searchOpt.county = shengshiqu[2]
  }

  if (cangkuid) {
    searchOpt.cangkuid = cangkuid
  }

  if (wuliu_sn) {
    searchOpt.wuliu_sn = wuliu_sn
  }

  if (dateRang && dateRang.length) {
    searchOpt.starttime = dateRang[0]
    searchOpt.endtime = dateRang[1]
  }

  if (yanhuoRang && yanhuoRang.length) {
    searchOpt.yanhuo_stime = yanhuoRang[0]
    searchOpt.yanhuo_etime = yanhuoRang[1]
  }

  if (postcode) {
    searchOpt.postcode = postcode
  }

  if (userid) {
    searchOpt.userid = userid
  }

  let res = await getOrderList(searchOpt)

  if (res.code == 200) {
    lists.value = res.data.map((v) => {
      return {
        ...v,
        statusText: statusTextArr.value[parseInt(v.status) + 1],
        statusStyle: statusStyleArr.value[parseInt(v.status) + 1]
      }
    })
    total.value = parseInt(res.msg)
  }
}

// 搜索
const searchForm = ref()
const statusArr = ref([
  {
    label: '全部',
    value: ''
  },
  {
    label: '已取消',
    value: '-1'
  },
  {
    label: '待审核',
    value: '0'
  },
  {
    label: '待取件',
    value: '1'
  },
  {
    label: '待收货',
    value: '2'
  },
  {
    label: '待验货',
    value: '3'
  },
  {
    label: '待打款',
    value: '4'
  },
  {
    label: '已打款',
    value: '5'
  }
])
const search = ref({
  status: '',
  name: '',
  tel: '',
  isbn: '',
  shengshiqu: [],
  cangkuid: '',
  wuliu_sn: '',
  dateRang: [],
  yanhuoRang: []
})

const resetFun = () => {
  search.value = {
    status: '',
    name: '',
    tel: '',
    isbn: '',
    shengshiqu: [],
    wuliu_sn: '',
    dateRang: [],
    yanhuoRang: []
  }
  getLists()
}

// 省市区
const handleChange = (value) => {
  search.value.shengshiqu = value ? [CodeToText[value[0]], CodeToText[value[1]], CodeToText[value[2]]] : []
  getLists()
}

//pageSize改变
function handleSizeChange(val) {
  pageSize.value = val
  getLists()
}

//pageNo改变
function handleCurrentChange(val) {
  pageNo.value = val
  getLists()
  // this.$store.dispatch('setpageNo', val);
}

//上一页
function handlePrev(val) {
  pageNo.value = val
  getLists()
}

//下一页
function handleNext(val) {
  pageNo.value = val
  getLists()
}

// *********************************************添加编辑
const showAddEdit = ref(false) //显示隐藏弹框
const addEditStatus = ref('add') //添加编辑状态
const addEditData = ref({
  id: '',
  name: '',
  images: [],
  isbn: '',
  type: '',
  zhongliang: '',
  dingjia: '',
  chubantime: '',
  price: '',
  caigouprice: '',
  weihuren: '',
  caigoucount: '',
  zuozhename: '',
  zuozhejieshao: '',
  chubanshe: '',
  shujijieshao: '',
  doubanScore: '',
  doubannumScore: ''
})

//添加文章
function addLists() {
  addEditData.value = {
    id: '',
    name: '',
    images: [],
    isbn: '',
    type: '',
    zhongliang: '',
    dingjia: '',
    chubantime: '',
    price: '',
    caigouprice: '',
    weihuren: '',
    caigoucount: '',
    zuozhename: '',
    zuozhejieshao: '',
    chubanshe: '',
    shujijieshao: '',
    doubanScore: '',
    doubannumScore: ''
  }
  addEditStatus.value = 'add'
  showAddEdit.value = true
}

//添加编辑文章回调
function hideAddEdit(type) {
  showAddEdit.value = false
  if (type != 'cancel') {
    getLists()
  }
}

//编辑文章
function editFun(item) {
  const {
    id,
    name,
    images,
    isbn,
    type,
    zhongliang,
    dingjia,
    chubantime,
    price,
    caigouprice,
    weihuren,
    caigoucount,
    zuozhename,
    zuozhejieshaom,
    chubanshe,
    shujijieshao,
    doubanScore,
    doubannumScore
  } = item
  addEditData.value = {
    id,
    name,
    images: images
      ? images.split(',').map((v) => {
        return {
          name: v,
          url: v
        }
      })
      : '',
    isbn,
    type,
    zhongliang,
    dingjia,
    chubantime,
    price,
    caigouprice,
    weihuren,
    caigoucount,
    zuozhename,
    zuozhejieshaom,
    chubanshe,
    shujijieshao,
    doubanScore,
    doubannumScore
  }
  addEditStatus.value = 'edit'
  showAddEdit.value = true
}

//删除文章
function deleteFun(id, index) {
  ElMessageBox.confirm('确定删除书籍?')
    .then(async () => {
      let res = await delteShangpin({ id })
      if (res.code == 200) {
        getLists()
      }
    })
    .catch(() => { })
}

//查看详情
const rowCli = (row, column) => {
  historyStore.setHistory({ key: route.path, search: search.value, pageNo: pageNo.value, pageSize: pageSize.value })
  router.push({ path: '/home/orderDetail', query: { order_sn: row.order_sn } })
}

// 比价
const bijiaFun = (isbn) => {
  window.open(
    `https://s.taobao.com/search?q=${isbn}&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.jianhua.201856-taobao-item.2&ie=utf8&initiative_id=tbindexz_20170306&sort=sale-desc`
  )
}

// 改变状态
const showStatus = ref(false)
const statusId = ref('')
const changeStatusFun = (id) => {
  statusId.value = id
  showStatus.value = true
}
const hideStatus = (type) => {
  if (type == 'complete') {
    getLists()
  }
  showStatus.value = false
}

// 获取书籍类型
const types = ref([])
const getTypes = async () => {
  let res = await getShujiType()

  if (res.code == 200) {
    types.value = res.data.map((v) => {
      return {
        label: v.name,
        value: v.id + ''
      }
    })
  }
}

// 员工列表
const persons = ref([])
const getPersons = async () => {
  let res = await getServerUserList()

  if (res.code == 200) {
    persons.value = res.data.map((v) => {
      return {
        label: v.username,
        value: v.id + ''
      }
    })
  }
}

// 行颜色
const tableRowClassName = ({ row, rowIndex }) => {
  if (row.userOrderCount > 3) {
    return 'warning-row'
  }
  return ''
}

// 仓库列表
const cangkus = ref([])
const getMyCangkuListFun = async () => {
  let res = await getMyCangkuList()
  if (res.code == 200) {
    cangkus.value = res.data.map((v) => {
      return {
        label: v.name,
        value: v.id
      }
    })
  }
}

// 获取物流信息
const wuliuData = ref('')
const wuliuShow = ref(false)
const wuliuStatus = ref('wuliu')
const wuliu_sn = ref('')
const getWuliu = (row, type) => {
  wuliuShow.value = true
  wuliuData.value = row.qujianren
  wuliuStatus.value = type
  wuliu_sn.value = row.wuliu_sn
}

const wuliuHide = () => {
  wuliuShow.value = false
}

// 备注
const beizhuChange = async (ordersn, beizhu) => {
  let res = await UpdateOrderHoutaibei({ ordersn, beizhu })

  if (res.code) {
    ElMessage({
      message: '操作成功!',
      type: 'success'
    })

    getLists()
  }
}

// 重推德邦
const againDebangWuliuFun = async (id) => {
  ElMessageBox.confirm(
    '确认重推德邦吗?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      let res = await againDebangWuliu({ id })

      if (res.code == 200) {
        ElMessage({
          type: 'success',
          message: `操作成功!`
        })

        getLists()
      }
    })
    .catch(() => {
    })

}

// 重推京东
const againJingDongWuliuFun = async (id) => {
  ElMessageBox.confirm(
    '确认重推京东吗?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      let res = await AgainJingJDWuliu({ id })

      if (res.code == 200) {
        ElMessage({
          type: 'success',
          message: `操作成功!`
        })

        getLists()
      }
    })
    .catch(() => {
    })

}

// 导出表格
const exportTableFun = () => {
  let tableData = lists.value.map((v) => {
    return {
      订单号: v.order_sn,
      仓库名: v.cangkuname,
      数量: v.shujishuliang,
      总价: v.price,
      时间: v.createtime,
      用户名称: v.username,
      取件人名称: v.consignee,
      联系电话: v.tel,
      订单状态: v.statusText,
      联系地址: `${v.province}/${v.city}/${v.county}`,
      详细地址: v.postcode,
      物流公司: v.wuliu_name,
      物流单号: v.wuliu_sn,
      后台备注: v.houtaibeizhu
    }
  })

  exportTable(tableData, `订单列表`)
}

onMounted(() => {
  if (historyStore.history && historyStore.history.key == route.path) {
    search.value = historyStore.history.search
    pageNo.value = historyStore.history.pageNo
    pageSize.value = historyStore.history.pageSize
  }
  historyStore.removeHistory()

  getLists()
  getTypes()
  getPersons()
  getMyCangkuListFun()
})
</script>
<style lang="scss" scoped>
.order-box {
  .left-right-box {
    position: absolute;
    top: 172px;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;

    .left-box {
      height: 100%;
      width: 230px;
      overflow-y: auto;
      overflow-x: hidden;
      padding-top: 50px;
      box-sizing: border-box;
      border: 1px solid #ebeef5;
      position: relative;
      overflow-y: auto;
      border-radius: 4px;
      margin-right: 20px;

      .title {
        font-size: 14px;
        padding: 8px 17px;
        color: #636363;
        height: 32px;
        line-height: 32px;
        font-weight: 600;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        background: #fff;
        z-index: 999;

        .icon {
          float: right;
          font-size: 24px;
          font-weight: 400;
          cursor: pointer;
        }
      }

      .left-lists {
        font-size: 12px;
        padding: 8px 17px;
        color: #636363;
        height: 32px;
        line-height: 32px;
        cursor: pointer;
        position: relative;

        .name {
          float: left;
        }

        .input-name {
          width: 90px;
          float: left;
          padding: 0;

          .el-input__inner {
            padding: 0 10px;
          }
        }

        .option {
          float: right;
        }
      }
    }

    .left-lists.active {
      color: #4c9ff2 !important;
      background-color: #f5f5f5;
    }

    .right-box {
      flex: 1;
      overflow-y: auto;
    }
  }
}
</style>
<style lang="scss">
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
</style>
